﻿using System;
using System.Reflection;
using Core.Model;
using DapperExtensions;
using DapperExtensions.Mapper;
using log4net;

namespace DataServer.Dao
{
    public class UserDao : BaseDao<User>
    {
        private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static UserMapper _userMapper;

        public UserDao()
        {
            if (_userMapper == null)
            {
                _userMapper = new UserMapper();
            }
        }

        protected override string GetTableName()
        {
            if (_userMapper != null)
                return _userMapper.TableName;
            return "user_info";
        }

        public User GetEntityById(string id)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<User>(f => f.Id, Operator.Eq, id);
                User user = result?.Connection.Get<User>(predicate);
                return user;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public User GetEntityByName(string name)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<User>(f => f.Name, Operator.Eq, name);
                User user = result?.Connection.Get<User>(predicate);
                return user;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }
    }
    public sealed class UserMapper : ClassMapper<User>
    {
        public UserMapper()
        {
            Table("user_info");
            Map(x => x.Id).Key(KeyType.Assigned);
            Map(x => x.UpdateTime).Ignore();
            //Ignore this property entirely
            //optional, map all other columns
            AutoMap();
        }
    }
}
